package com.grasp.activity;

import java.util.HashMap;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.view.KeyEvent;
import android.view.View;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TabHost;

import com.grasp.activity.area.AreaMainFragment;
import com.grasp.activity.device.DeviceMainFragment;
import com.grasp.activity.scene.SceneMainFragment;
import com.grasp.activity.set.SetMainFragment;
import com.grasp.base.Logger;

public class MainActivity extends FragmentActivity {

	public static final String SENCE_TAB = "sence";
	public static final String AREA_TAB = "area";
	public static final String DEVICE_TAB = "device";
	public static final String SETTING_TAB = "setting";

	private TabHost mTabHost;
	private TabManager mTabManager;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Logger.d(this.getClass().getName() + "-->onCreate()");

		setContentView(R.layout.activity_main);
		initTabBar();
		mTabHost = (TabHost) findViewById(android.R.id.tabhost);
		mTabHost.setup();
		mTabManager = new TabManager(this, mTabHost, R.id.realtabcontent);
		mTabManager.addTab(
				mTabHost.newTabSpec(SENCE_TAB).setIndicator("sence"),
				SceneMainFragment.class, null);
		mTabManager.addTab(mTabHost.newTabSpec(AREA_TAB).setIndicator("area"),
				AreaMainFragment.class, null);
		mTabManager.addTab(
				mTabHost.newTabSpec(DEVICE_TAB).setIndicator("device"),
				DeviceMainFragment.class, null);
		mTabManager.addTab(
				mTabHost.newTabSpec(SETTING_TAB).setIndicator("setting"),
				SetMainFragment.class, null);
		mTabHost.setCurrentTabByTag(SENCE_TAB);
	}

	private void initTabBar() {
		RadioGroup radioGroup = (RadioGroup) findViewById(R.id.main_radioGroup);
		radioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(RadioGroup group, int checkedId) {
				switch (checkedId) {
				case R.id.main_radio_btn_sence:
					mTabHost.setCurrentTabByTag(SENCE_TAB);
					break;
				case R.id.main_radio_btn_area:
					mTabHost.setCurrentTabByTag(AREA_TAB);
					break;
				case R.id.main_radio_btn_device:
					mTabHost.setCurrentTabByTag(DEVICE_TAB);
					break;
				case R.id.main_radio_btn_setting:
					mTabHost.setCurrentTabByTag(SETTING_TAB);
					break;
				}
			}
		});
	}

	@Override
	protected void onStart() {
		super.onStart();
		Logger.d(this.getClass().getName() + "-->onStart()");
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		Logger.d(this.getClass().getName() + "-->onStart()");
	}
	
	@Override
	protected void onPause() {
		super.onPause();
		Logger.d(this.getClass().getName() + "-->onPause()");
	}

	public static class TabManager implements TabHost.OnTabChangeListener {
		private final FragmentActivity mActivity;
		private final TabHost mTabHost;
		private final int mContainerId;
		private final HashMap<String, TabInfo> mTabs = new HashMap<String, TabInfo>();
		TabInfo mLastTab;

		static final class TabInfo {
			private final String tag;
			final Class<?> clss;
			private final Bundle args;
			private Fragment fragment;

			TabInfo(String _tag, Class<?> _class, Bundle _args) {
				tag = _tag;
				clss = _class;
				args = _args;
			}
		}

		static class DummyTabFactory implements TabHost.TabContentFactory {
			private final Context mContext;

			public DummyTabFactory(Context context) {
				mContext = context;
			}

			@Override
			public View createTabContent(String tag) {
				View mView = new View(mContext);
				mView.setMinimumWidth(0);
				mView.setMinimumHeight(0);
				return mView;
			}
		}

		public TabManager(FragmentActivity activity, TabHost tabHost,
				int containerId) {
			mActivity = activity;
			mTabHost = tabHost;
			mContainerId = containerId;
			mTabHost.setOnTabChangedListener(this);
		}

		public void addTab(TabHost.TabSpec tabSpec, Class<?> clss, Bundle args) {
			tabSpec.setContent(new DummyTabFactory(mActivity));
			String tag = tabSpec.getTag();

			TabInfo info = new TabInfo(tag, clss, args);

			info.fragment = mActivity.getSupportFragmentManager()
					.findFragmentByTag(tag);
			if (info.fragment != null && !info.fragment.isDetached()) {
				FragmentTransaction ft = mActivity.getSupportFragmentManager()
						.beginTransaction();
				ft.detach(info.fragment);
				ft.commit();
			}

			mTabs.put(tag, info);
			mTabHost.addTab(tabSpec);
		}

		@Override
		public void onTabChanged(String tabId) {
			TabInfo newTab = mTabs.get(tabId);
			if (mLastTab != newTab) {
				FragmentTransaction ft = mActivity.getSupportFragmentManager()
						.beginTransaction();
				if (mLastTab != null) {
					if (mLastTab.fragment != null) {
						ft.detach(mLastTab.fragment);
					}
				}
				if (newTab != null) {
					if (newTab.fragment == null) {
						newTab.fragment = Fragment.instantiate(mActivity,
								newTab.clss.getName(), newTab.args);
						ft.add(mContainerId, newTab.fragment, newTab.tag);
					} else {
						ft.attach(newTab.fragment);
					}
				}
				mLastTab = newTab;
				ft.commit();
				mActivity.getSupportFragmentManager()
						.executePendingTransactions();
			}
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			AlertDialog dialog = new AlertDialog.Builder(this)
					.setMessage(getString(R.string.sure_exit_str))
					.setPositiveButton(R.string.sure_str,
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									finish();
								}
							})
					.setNegativeButton(R.string.clear_str,
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
								}
							}).create();
			dialog.setCanceledOnTouchOutside(true);
			dialog.show();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

}
